<template>
  <uni-nav-bar title="车队充值" left-icon="left" @clickLeft="navBack" :fixed="true" statusBar></uni-nav-bar>
  <view class="recharge column" style="color:#fff;justify-content:flex-start;">
    <view style="margin-top:60rpx;">账户总额</view>
    <view style="margin-top:15rpx;font-size: 50rpx;"><text
        style="font-size: 23rpx;">￥</text>{{userInfo.getFleetAll.money}}</view>
  </view>
  <view class="package">
    <view>充值金额(单位：吨)</view>
    <view class="space-between">
      <view v-for="(item,index) in list" :key="index" class="column lis"
        :style="{background:active===item.amount?'#1D8DFF':'',color:active===item.amount?'#fff':''}"
        @click="change(item)">
        <view style="font-size:36rpx;">{{item.amount}}吨</view>
        <view>{{item.money}}元</view>
      </view>
    </view>
  </view>
  <view class="package space-between" v-if="positionAll">
    <view class="direction-start">
      <view>{{positionAll.name}}</view>
      <view style="margin-top:5rpx;">当前地区价格{{price}}元/吨</view>
    </view>
    <view style="color:#1B91FF;" @click="navTo('fleet/money/locaList')">地区差异表>></view>
  </view>
  <view class="but" @click="recharge()">充值</view>
  <view style="width: 90%;margin:0px auto;">点击充值表示已经确认阅读并同意<text style="color:#1B91FF;"
      @click="navTo('fleet/money/rule')">《充值规则》</text>
  </view>
  <!-- 获取当前经纬度 -->
  <Lotlats @position="position"></Lotlats>
</template>

<script setup lang="ts">
  import { navBack, navTo } from '@/utils/navigator';
  import { ref } from 'vue';
  import { GetCities } from '@/gql/team';
  import { errorToast, showLoading } from '@/utils/prompt';
  import { toPublish } from '@mqtt';
  import Lotlats from '@c/team/Lotlat.vue';
  import { getRechargeData } from '@/gql/fleet';
  import { useUserStore } from '@/stores/user';
  import { getDriverID } from '@/stores/driverID';
  const userInfo = useUserStore();
  const driver_id = getDriverID();
  /**
   * 车队充值
   * @param {Array} list 加注信息列表
   * @param {Number} active 当前选中的加注信息
   * @param {String} money 当前选择的金额
   * @param {Object} positionAll 当前城市信息
   * @param {String} price 地区单价
   * @param {String} orderID 加注订单ID
   */
  const list = ref([])
  const active = ref(0)
  const money = ref('')
  const positionAll = ref()
  const price = ref('')
  const orderID = ref('')
  function init(code : string) {
    showLoading()
    const payload = {
      query: getRechargeData,
      variables: {
        fleet_id: Number(userInfo.getFleetAll.id),
        code
      },
    };
    toPublish(
      'ql/driver/getRechargeData',
      payload,
      (obj : any) => {
        const { getRechargeData } = obj.data;
        price.value = getRechargeData.price
        list.value = getRechargeData.data
        active.value = getRechargeData.data[0].amount
        money.value = getRechargeData.data[0].money
      }
    );
  }
  /**
   * 获取当前城市信息
   * @param {Number} lat 当前位置的纬度
   * @param {Number} lot 当前位置的经度
   */
  function position(lats : number, lots : number) {
    if (!positionAll.value) {
      sub(lots, lats);
    }
  }
  /**
   * 获取当前位置信息
   * @param {Number} lon 当前驻车地址位置的经度
   * @param {Number} lat 当前驻车地址位置的纬度
   */
  function sub(lon : number, lat : number) {
    showLoading('正在加载');
    const payload = {
      query: GetCities,
      variables: {
        lon,
        lat,
      },
    };
    toPublish('ql/team/getCity', payload, (obj : any) => {
      uni.hideLoading();
      const { data } = obj;
      positionAll.value = data.get_city;
      init(data.get_city.code)
    });
  }
  function change(num : any) {
    active.value = num.amount
    money.value = num.money
  }
  function recharge() {
    showLoading()
    const payload = {
      fleet_id: Number(userInfo.getFleetAll.id),
      code: positionAll.value.code,
      driver_id,
      amount: active.value,
      method: 'mp'
    };
    toPublish(
      'driver/addFleetRecharge',
      payload,
      (obj : any) => {
        const { order_id } = obj.data;
        orderID.value = order_id
        launchPayment(order_id)
      }
    );
  }
  function launchPayment(order : string) {
    showLoading()
    const payload = {
      order_id: order
    };
    toPublish(
      'driver/payFleetWechat',
      payload,
      (obj : any) => {
        paymentHandler(obj)
      }
    );
  }
  /**
     * 微信支付
     */
  function paymentHandler(obj : any) {
    if (obj.code === 1) {
      // @ts-ignore
      WeixinJSBridge.invoke('getBrandWCPayRequest', obj.data, function (res : any) {
        switch (res.err_msg) {
          case 'get_brand_wcpay_request:ok':
            userInfo.fleetUser()
            navTo('fleet/money/success?money=' + money.value + '&orderID=' + orderID.value)
            break;
          case 'get_brand_wcpay_request:cancel':
            errorToast('充值取消');
            break;
          case 'get_brand_wcpay_request:fail':
            errorToast('充值失败');
            break;
        }
        // if (res.err_msg == 'get_brand_wcpay_request:ok') {
        //   // 使用以上方式判断前端返回,微信团队郑重提示：
        //   //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
        // }
      });
    } else {
      errorToast(obj.msg);
    }
  }
</script>

<style scoped lang="less">
  .recharge {
    background-image: url(https://admin.anlan.tech/uploads/20221023/aa78cfcec92006930c355b1305a5dbaf.png);
    background-repeat: no-repeat;
    background-size: contain;
    width: 722rpx;
    height: 268rpx;
    margin: 15rpx auto;
  }

  .lis {
    margin-top: 40rpx;
    width: 32%;
    padding: 10rpx 0rpx;
    border: 1px solid #1F93FF;
    box-sizing: border-box;
    border-radius: 5px;
    color: #1F93FF;
  }

  .but {
    width: 90%;
    margin: 30rpx auto;
    background-color: #1F93FF;
    color: #fff;
    border-radius: 5px;
    text-align: center;
    height: 91rpx;
    line-height: 91rpx;
  }
</style>